package cn.jiaxu.musicplayer2;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {
    public static  int PLAY=1;
    public static  int PAUSE=2;
    public static  int RESUME=3;
    private boolean flag = true;
    private MyService.MyBinder mm;
    private Handler handler;
    private SeekBar sb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sb = (SeekBar) findViewById(R.id.sb);
        Intent intent = new Intent("mymusic");
        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mm = (MyService.MyBinder)service;
                Thread th = new Thread(){
                    @Override
                    public void run() {
                        int pro=0;
                        while(pro<=600 && flag) {
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            pro = mm.getProgress();
                            Message message = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putInt("pro",pro);
                            message.setData(bundle);

                            handler.sendMessage(message);
                        }
                    }
                };
                th.start();
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        },BIND_AUTO_CREATE);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                int s = msg.getData().getInt("pro");
                sb.setProgress(s);
            }
        };
    }

    public void play(View view) {
        Intent intent = new Intent("mymusic");
        intent.putExtra("service",PLAY);
        startService(intent);
    }

    public void pause(View view) {
        Intent intent = new Intent("mymusic");
        intent.putExtra("service",PAUSE);
        startService(intent);
    }
    public void resume(View view) {
        Intent intent = new Intent("mymusic");
        intent.putExtra("service",RESUME);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        flag=false;
    }
}
